package com.hua.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.hua.common.SendMessageTool;
import com.hua.common.ValidateCodeUtils;
import com.hua.entities.R;
import com.hua.entities.User;
import com.hua.service.serviceImpl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RequestMapping("/user")
@Slf4j
@RestController
public class UserController {

  @Autowired
  private UserServiceImpl userService;

  @Autowired
  private RedisTemplate redisTemplate;
  @PostMapping("/sendMsg")
  public R<String>  getInfo(@RequestBody User user, HttpSession session){

    //获取手机号
    String phone = user.getPhone();
    if(StringUtils.isNotEmpty(phone)){
      //随机生成4位验证码
      String code = ValidateCodeUtils.generateValidateCode(4).toString();
      log.info(code);
      //调用API完成
//      SendMessageTool.sendMessage("和你有缘无份个人公众号","+86"+phone,code,"5");
      //生成验证码保存起来
//      session.setAttribute(phone,code);
      //优化，将生成的验证码存放到redis中，有效期5分钟
      redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
//      session.setMaxInactiveInterval(5);
      return R.success("发送成功~~");
    }
    return R.error("发送失败~~~");
  }

  @PostMapping("/login")
  //返回user是因为需要在浏览器保存一份用户信息
  public R<User> login(@RequestBody Map map,HttpSession session){
    log.info(map.toString());
    //获取手机：
    String phone = map.get("phone").toString();
    //获取验证码
    String code = map.get("code").toString();

    //取出发送的验证码
//    String codeFirst = session.getAttribute(phone).toString();
    //从redis中获取
    String codeFirst = (String) redisTemplate.opsForValue().get(phone);
//    System.out.println("取出来"+codeFirst);
    if(codeFirst!=null && codeFirst.equals(code)){
      LambdaQueryWrapper<User>queryWrapper=new LambdaQueryWrapper<>();
      queryWrapper.eq(User::getPhone,phone);
      //查询用户是否在数据库中存在，若不存在，自动注册
      User user = userService.getOne(queryWrapper);
      if(user==null){
        user = new User();
        user.setPhone(phone);
        user.setStatus(1);
        userService.save(user);
      }
      //将用户保存到session中,防止登录成功也被拦截下来
      session.setAttribute("userPhone",user);
//      System.out.println(session.getAttribute("userPhone"));
      //若登录成功则删除验证码
      redisTemplate.delete(phone);
//      System.out.println("登录成功后查看，验证码有无删除成功:"+redisTemplate.opsForValue().get(phone));
      return R.success(user);
    }
    return R.error("登陆失败");
  }
}
